import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
import { getToken, setToken } from '@/utils/auth'
import { login, getInfo,getRedbagInfoCode } from '@/api/auth'
import { getUserInfo } from '@/api/user'
// import fastClick from 'fastclick'
import Vant from 'vant';
import { Lazyload } from 'vant'
import 'vant/lib/index.css'
import '@/assets/css/common.css'
import {getIndexUrl, isWeiXin, getQueryVariable, getRedbagUrl, redirectUrlCode} from '@/utils/app'
import VueWechatTitle from 'vue-wechat-title' 
import { Toast } from 'vant';
import LuckDraw from 'vue-luck-draw'
Vue.use(LuckDraw)
// fastClick.attach(document.body)
Vue.config.productionTip = false
Vue.use(Vant)
Vue.use(Lazyload)
Vue.use(VueWechatTitle)

let path = process.env.VUE_APP_PATH
router.beforeEach((to, from, next) => {
  
  let href = window.location.href;
  console.log(href.includes("code="))
  console.log(href.includes("codeq="))
  if (href.includes("code=") && !href.includes('codeq=')) {
    let url = redirectUrlCode()
    console.log(url)
    window.location.href = url
    next(false) 
    return 
  }
  // return ;
  console.log(to)
  if(to.query.codeq) {
    Toast.loading({
      message: '加载中...',
      forbidClick: false,
      duration: 10000
    });
    console.log(to)
    if(to.query.redbag == 1) {
      to.query.qq = 'rebbag'
      getRedbagInfoCode({code: to.query.codeq, ...to.query}).then(res=>{
        Toast.clear()
        if(!res.access_token) {
          Toast('网络错误');
        }else {
          store.commit('SET_REBBAG_USER', res.user)
          window.location.href = getRedbagUrl(to.query.q)
        }
      })
    }else {
      getInfo({code: to.query.codeq, ...to.query}).then(res=>{
        Toast.clear()
        if(!res.access_token) {
          Toast('网络错误');
        }else {
          setToken(res.access_token)
          store.commit('SET_USER', res.user)
          window.location.href = getIndexUrl(to.query.q)
        }
      })
    }
  	
    next(false) 
    return
  }else{
    let token = getToken()
    if(!token && to.meta.requiresAuth && isWeiXin()) {
      Toast.loading({
        message: '加载中...',
        forbidClick: false,
        duration: 10000
      });
      login({redirect: window.location.href, scopes: 'snsapi_userinfo'}).then(res=>{
        Toast.clear()
        console.log(res)
        window.location.href = res
      })
      next(false)
      return 
    }else if(token) {//更新token
      getUserInfo().then(res=>{
        Toast.clear()
        store.commit('SET_USER', res)
        next()
      })
    }else{
      next()
    }
  }
})
new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app')
